<!--
* @description 点位类别编辑
* @author zywu
* @date 2021/03/18 10:27:13
!-->
<template>
  <el-form
    class="form-pointType"
    label-width="120px"
    :model="dataForm"
    :rules="dataRules"
    ref="dataForm"
    @submit.native.prevent
  >
    <el-form-item label="类别名称：" prop="name">
      <el-input v-model="dataForm.name" auto-complete="off" placeholder="不要重复" clearable></el-input>
    </el-form-item>
    <el-card v-for="(item,i) in dataForm.dataList" :key="i" :class="{ 'is-saved':item.saved }">
      <div slot="header" class="d-flex ai-center jc-between">
        <span class="d-flex ai-center">
          <span class="order d-flex ai-center jc-center">{{i+1}}</span>
          <span v-if="!item.saved">检查内容{{i+1}}</span>
          <template v-else>
            <span class="item-type">{{checkTypes[item.checkType]}}</span>
            <span class="item-name">{{item.name}}</span>
          </template>
        </span>
        <span v-if="item.saved" class="card-edit">
          <el-button type="text" @click="handleEdit(i)">编辑</el-button>
          <el-button type="text" @click="handleDel(i)">删除</el-button>
        </span>
      </div>
      <div v-show="!item.saved">
        <el-form-item label="内容名称：" :prop="'dataList.'+i+'.name'" :rules="dataRules.itemName">
          <el-input v-model="item.name" auto-complete="off" placeholder="请输入检查内容名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="检查类型：" :prop="'dataList.'+i+'.checkType'" :rules="dataRules.checkType">
          <el-radio-group v-model="item.checkType">
            <el-radio :label="1">合格/不合格类</el-radio>
            <el-radio :label="2">单选类</el-radio>
            <el-radio :label="3">填值类</el-radio>
            <el-radio :label="4">拍照类</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="item.checkType==1">
          <el-input value="A：合格" disabled style="width:120px;"></el-input>
          <el-input value="B：不合格" disabled style="margin-left:20px;width:120px;"></el-input>
        </el-form-item>
        <template v-else-if="item.checkType==2">
          <el-form-item
            v-for="(option,j) in item.selectOptions"
            :key="j"
            :prop="'dataList.'+i+'.selectOptions.'+j+'.option'"
            :rules="dataRules.optionText"
          >
            <div class="row-option d-flex ai-center">
              <el-input v-model="option.option" auto-complete="off" placeholder="请输入选项" clearable></el-input>
              <el-checkbox v-model="option.notOk">设为不合格</el-checkbox>
              <i class="btn-grid el-icon-plus" @click="handleAddOption(item,j)"></i>
              <i v-if="item.selectOptions.length>2" class="btn-grid el-icon-minus" @click="handleDelOption(item,j)"></i>
            </div>
          </el-form-item>
        </template>
        <template v-else-if="item.checkType==3">
          <el-row :gutter="5" style="padding-left:110px;">
            <el-col :span="8">
              <el-form-item label="上限:" label-width="70px" :prop="'dataList.'+i+'.max'" :rules="dataRules.min">
                <el-input-number v-model="item.max" :controls="false" placeholder="请输入数字" clearable></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="下限:" label-width="70px" :prop="'dataList.'+i+'.min'" :rules="dataRules.max">
                <el-input-number v-model="item.min" :controls="false" placeholder="请输入数字" clearable></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="单位:" label-width="70px" :prop="'dataList.'+i+'.unit'" :rules="dataRules.unit">
                <el-input v-model="item.unit" auto-complete="off" placeholder="请输入，比如米" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-form-item
          v-else-if="item.checkType==4"
          label="最少拍照数量："
          label-width="140px"
          :prop="'dataList.'+i+'.picNum'"
          :rules="dataRules.picNum"
          style="padding-left:120px;"
        >
          <el-input-number
            v-model="item.picNum"
            :controls="false"
            :max="9"
            :min="1"
            :precision="0"
            placeholder="请输入数字，不超过9"
            clearable
            style="width:200px;"
          ></el-input-number>&nbsp;张
        </el-form-item>
      </div>
      <div v-show="item.saved">
        <div v-if="item.checkType==1">
          <p>A：合格</p>
          <p>B：不合格</p>
        </div>
        <div v-else-if="item.checkType==2">
          <p v-for="(option,j) in item.selectOptions" :key="j">
            {{labels.substr(j,1)}}：{{option.option}}
            <span
              style="margin-left:10px;color:#999;"
            >{{!option.notOk?'合格选项':'不合格选项'}}</span>
          </p>
        </div>
        <div v-else-if="item.checkType==3">
          <p>{{item.min}}~{{item.max}}{{item.unit}}</p>
        </div>
        <div v-else-if="item.checkType==4">
          <p>需至少拍{{item.picNum}}张照片</p>
        </div>
      </div>
      <div v-show="!item.saved" class="d-flex ai-center jc-end" style="margin-bottom:20px;">
        <el-button type="primary" size="small" @click="handleSave(2,i)">确定</el-button>
        <el-button v-if="!isEdit" size="small" @click="handleDel(i)">取消</el-button>
      </div>
    </el-card>
    <el-form-item label-width="0" class="verifyidentity-button">
      <el-button round @click="handleClose()">取消</el-button>
      <el-button type="primary" round plain @click="handleSave(3)">添加检查内容</el-button>
      <el-button type="primary" round @click="handleSave()">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapState } from 'vuex'
import {
  addInspectPointType,
  updatePointType,
  getPointTypeInfo,
} from '@/api/inspectx'
const labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
let deleteContentIds = []
export default {
  props: {
    editInfo: {
      type: Object,
      required: false,
    },
    handleClose: {
      type: Function,
      required: true,
    },
  },
  computed: {
    ...mapState(['userinfo']),
    isEdit() {
      return !!this.dataForm.id
    },
  },
  data() {
    return {
      labels,
      checkTypes: ['', '合格不合格类', '单选类', '填值类', '拍照类'],
      dataForm: {
        name: '',
        dataList: [],
      },
      dataRules: {
        name: [{ required: true, message: '请输入' }],
        itemName: [{ required: true, message: '请输入' }],
        checkType: [{ required: true, message: '请选择' }],
        optionText: [{ required: true, message: '请输入' }],
        min: [{ required: true, message: '请输入' }],
        max: [{ required: true, message: '请输入' }],
        unit: [{ required: true, message: '请输入' }],
        picNum: [{ required: true, message: '请输入' }],
      },
    }
  },

  components: {},

  created() {
    let { id, pointTypeName } = this.editInfo
    if (id) {
      this.dataForm.id = id
      this.dataForm.name = pointTypeName
      getPointTypeInfo({
        pointTypeId: id,
      }).then((res) => {
        this.dataForm.dataList = res.data.contents.map((n) => {
          n.selectOptions = [{}, {}]
          if (n.checkType == 2) {
            n.selectOptions = n.options.map((m) => {
              m.notOk = m.isOk == 1 ? false : true
              return m
            })
          } else if (n.checkType == 3) {
            if (n.options[1]) {
              n.max = Number(n.options[1].option)
            }
            if (n.options[0]) {
              n.min = Number(n.options[0].option)
            }
            if (n.options[2]) {
              n.unit = n.options[2].option
            }
          } else if (n.checkType == 4) {
            n.picNum = Number(n.options[0].option || 1)
          }
          n.saved = true
          return n
        })
      })
    }
  },

  mounted() {},

  methods: {
    handleEdit(i) {
      this.$set(this.dataForm.dataList[i], 'saved', false)
    },
    handleAdd() {
      this.dataForm.dataList.push({
        name: '',
        checkType: '',
        selectOptions: [
          {
            notOk: false,
            option: '',
          },
          {
            notOk: false,
            option: '',
          },
        ],
      })
    },
    handleDel(i) {
      let item = this.dataForm.dataList[i]
      if (item.id) {
        deleteContentIds.push(item.id)
      }
      this.dataForm.dataList.splice(i, 1)
    },
    handleAddOption(item, j) {
      item.selectOptions.splice(j + 1, 0, {
        notOk: false,
        option: '',
      })
    },
    handleDelOption(item, j) {
      item.selectOptions.splice(j, 1)
      console.log(item.selectOptions)
    },
    formatData() {
      let { id, name, dataList } = this.dataForm
      return {
        id,
        name,
        orgId: this.isEdit ? undefined : this.userinfo.org.id,
        deleteContentIds: deleteContentIds.join(','),
        contents: dataList.map((n, i) => {
          let { name, checkType, selectOptions, min, max, unit, picNum } = n
          let options = []
          if (checkType == 1) {
            options = [
              {
                lable: 'A',
                option: '合格',
                isOk: 1,
              },
              {
                lable: 'B',
                option: '不合格',
                isOk: 2,
              },
            ]
          } else if (checkType == 2) {
            options = selectOptions.map((m, mi) => {
              return {
                lable: labels.substr(mi, 1),
                option: m.option,
                isOk: m.notOk ? 2 : 1,
              }
            })
          } else if (checkType == 3) {
            options = [
              {
                lable: '1',
                option: min,
                isOk: 1,
              },
              {
                lable: '2',
                option: max,
                isOk: 1,
              },
              {
                lable: '3',
                option: unit,
                isOk: 1,
              },
            ]
          } else if (checkType == 4) {
            options = [
              {
                lable: '1',
                option: picNum,
                isOk: 1,
              },
            ]
          }
          return {
            id: n.id,
            name,
            sort: i + 1,
            checkType,
            options,
          }
        }),
      }
    },
    handleSave(validFlag = 1, index) {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          let list = this.dataForm.dataList
          if (validFlag == 1) {
            if (list.length == 0) {
              return this.$message.warning('至少添加一项检查内容')
            } else if (
              list.length ==
              list.filter((n) => {
                return n.checkType == 4
              }).length
            ) {
              return this.$message.warning('不允许只有拍照类的检查内容')
            }
          }
          if (validFlag == 2) {
            let dataItem = list[index]
            if (dataItem.checkType == 2) {
              if (
                dataItem.selectOptions.filter((n) => {
                  return !n.notOk
                }).length == 0
              ) {
                return this.$message.warning('至少有一项为合格项')
              } else if (
                dataItem.selectOptions.filter((n) => {
                  return n.notOk
                }).length == 0
              ) {
                return this.$message.warning('至少有一项为不合格项')
              }
            } else if (dataItem.checkType == 3) {
              if (Number(dataItem.max) < Number(dataItem.min)) {
                return this.$message.warning('上限不能小于下限')
              }
            }
            this.$set(list[index], 'saved', true)
          } else if (validFlag == 3) {
            let unsaved = list.filter((n) => {
              return !n.saved
            })
            if (unsaved.length > 0) {
              return this.$message.warning('请先保存检查内容')
            }
            this.handleAdd()
          } else if (validFlag == 1) {
            let unsaved = list.filter((n) => {
              return !n.saved
            })
            if (unsaved.length > 0) {
              return this.$message.warning('请先保存检查内容')
            }
            let dao = this.isEdit ? updatePointType : addInspectPointType
            dao(this.formatData()).then((res) => {
              if (res.status == 200) {
                this.$message({
                  message: '保存成功',
                  type: 'success',
                })
                this.handleClose(true)
              } else {
                this.$message({
                  message: res.info,
                  type: 'error',
                })
              }
            })
          }
        }
      })
    },
  },
}
</script>
<style lang='scss'>
.form-pointType {
  .el-card {
    margin-bottom: 20px;
    .order {
      margin-right: 10px;
      width: 30px;
      height: 30px;
      border-radius: 15px;
      color: #fff;
      background: #409eff;
    }
    .card-edit {
      visibility: hidden;
      width: 120px;
      text-align: right;
    }
    &:hover {
      background: #ecf5ff;
      .card-edit {
        visibility: visible;
      }
    }
    &.is-saved {
      .el-card__body {
        padding-bottom: 20px;
      }
      .el-checkbox,
      .btn-grid {
        display: none;
      }
      .el-card__header {
        padding: 7px 20px;
      }
      p {
        margin: 5px 0;
        line-height: 20px;
      }
      .item-type {
        margin-right: 10px;
        color: #999;
      }
      .item-name {
        flex: 1;
      }
    }
  }
  .el-card__body {
    padding-bottom: 0;
  }
  .el-card__header {
    padding: 13px 20px;
  }
  .el-input-number {
    width: 100%;
    .el-input__inner {
      text-align: left;
    }
  }
  .row-option {
    .el-input {
      width: 300px;
    }
    .el-checkbox,
    .btn-grid {
      margin-left: 20px;
    }
  }
  .btn-grid {
    margin: 0 5px;
    width: 40px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    line-height: 40px;
    text-align: center;
    cursor: pointer;
  }
  .jc-end {
    justify-content: flex-end;
  }
}
</style>